#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''=================================================
@Project -> File   ：try -> MNIST
@IDE    ：PyCharm
@Author ：csl_forever
@Date   ：2020/9/12 21:20
@Desc   ：
=================================================='''
import sys, os
import numpy as np
from PIL import Image
from deep_learning_demo.dataset.mnist import load_mnist
import pickle
from 阶跃函数 import sigmod
from 三层神经网络 import softmax

sys.path.append(os.pardir)  # 为了导入父目录中的文件所做的设定


def img_show(img):
    pil_img = Image.fromarray(np.uint8(img))  # 数组到图像的转化
    pil_img.show()


(x_train, t_train), (x_test, t_test) = load_mnist(flatten=True, normalize=False)

img = x_train[0]
label = t_train[0]
# print(label)
#
# print(img.shape)
img = img.reshape(28, 28)


# print(img.shape)
#
# img_show(img)
def get_data():
    (x_train, t_train), (x_test, t_test) = load_mnist(normalize=True, flatten=True, one_hot_label=False)
    return x_test, t_test


def init_network():
    with open("sample_weight.pkl", 'rb') as f:
        network = pickle.load(f)
    return network


def predict(network, x):
    w1, w2, w3 = network['W1'], network['W2'], network['W3']
    b1, b2, b3 = network['b1'], network['b2'], network['b3']
    a1 = np.dot(x, w1) + b1
    z1 = sigmod(a1)
    a2 = np.dot(z1, w2) + b2
    z2 = sigmod(a2)
    a3 = np.dot(z2, w3) + b3
    y = softmax(a3)
    return y


x, t = get_data()
network = init_network()

accuracy_cnt = 0
for i in range(len(x)):
    y = predict(network, x[i])
    p = np.argmax(y)  # 获取概率最高的元素的索引
    if p == t[i]:
        accuracy_cnt += 1

print("Accuracy:" + str(float(accuracy_cnt) / len(x)))
